<?php

namespace app\api\controller\user;

use app\admin\model\Setting;
use app\api\controller\Controller;
use app\api\model\User as UserModel;
use app\api\model\Order as OrderModel;
use app\api\model\Setting as SettingModel;
use think\Db;
use think\Log;

/**
 * 个人中心主页
 * Class Index
 * @package app\api\controller\user
 */
class Index extends Controller
{
    /**
     * 获取当前用户信息
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $user = $this->getUser();
        $user['shanghui_name'] = Db::name('shanghui')->where('id',$user["shanghui_id"])->value("name"); //获取商会名称
        if (!$user['add_date'] || strtotime($user['add_date']) <= 0) {
            $user['lion_age'] = 0;
        } else {
            $user['lion_age'] = ceil(date('Y', time()) - date('Y', strtotime($user['add_date'])));//狮龄
        }
        $user['points_ranking'] = 1000;//我的积分排行
        $user['donate_ranking'] = 1000;//我的捐款排行
        //所有人积分排行
        $points_ranking = Db::name('shanghui_user')->where('shanghui_id', '=', $user["shanghui_id"])
        ->where('status', 90)
        ->order(['points' => 'desc', 'add_date' => 'ASC'])
        ->select()->toArray();
        foreach ($points_ranking as $k => $v) {
            if ($v['user_id'] == $user['user_id']) {
                $user['points_ranking'] = $k + 1;
                $user['points'] = $v['points'];  //积分
                $user['activity_count'] = $v['activity_count'];  //参加活动次数
            }
        }
        //所有人捐款排行
        $donate_ranking = Db::name('shanghui_user')->where('shanghui_id', '=', $user["shanghui_id"])
        ->where('status', 90)
        ->order(['donate' => 'desc', 'add_date' => 'ASC'])
        ->select()->toArray();
        foreach ($donate_ranking as $k => $v) {
            if ($v['user_id'] == $user['user_id']) {
                $user['donate_ranking'] = $k + 1;
                $user['donate'] = $v['donate'];
            }
        }

        $team = Db::name('team')->where('wxapp_id', $this->wxapp_id)->where('team_id', $user['team_id'])->find();
        $team['points_ranking'] = 10000;//所属服务队默认积分排名
        $team['donate_ranking'] = 10000;//所属服务队默认捐款排名
        $team['people_ranking'] = 10000;//所属服务队默认人数排名
        $team['people_nums'] = Db::name('user')->where('wxapp_id', $this->wxapp_id)->where('team_id', $user['team_id'])->count();//所属服务队当前队员总数
        $team_people_ranking = Db::name('user')
            ->where('team_id', '<>', 0)
            ->where('wxapp_id', $this->wxapp_id)
            ->field(['user_id', 'team_id', 'count(user_id) AS total_people'])
            ->group('team_id')
            ->order(['total_people' => 'desc'])
            ->select()
            ->toArray();
        foreach ($team_people_ranking as $k => $v) {
            if ($v['team_id'] == $user['team_id']) {
                $team['people_ranking'] = $k + 1;
            }
        }
        $team_points_ranking = Db::name('team')->where('wxapp_id', $this->wxapp_id)->order(['points' => 'desc', 'team_id' => 'ASC'])->select()->toArray();
        foreach ($team_points_ranking as $k => $v) {
            if ($v['team_id'] == $user['team_id']) {
                $team['points_ranking'] = $k + 1;
            }
        }
        $team_donate_ranking = Db::name('team')->where('wxapp_id', $this->wxapp_id)->order(['donate' => 'desc', 'team_id' => 'ASC'])->select()->toArray();
        foreach ($team_donate_ranking as $key => $value) {
            if ($value['team_id'] == $user['team_id']) {
                $team['donate_ranking'] = $key + 1;
            }
        }
        // 订单总数
        $model = new OrderModel;
        return $this->renderSuccess([
            'userInfo' => $user,
            'team' => $team,
            'orderCount' => [
                'payment' => $model->getCount($user, 'payment'),
                'received' => $model->getCount($user, 'received'),
                'comment' => $model->getCount($user, 'comment'),
            ],
            'setting' => [
                'points_name' => SettingModel::getPointsName(),
            ],
            'menus' => (new UserModel)->getMenus($user)   // 个人中心菜单列表
        ]);
    }

    /**
     * 我的报名
     * @param array $post
     * @return string
     */
    public function mySign()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        //$userInfo = Db::name('user')->find(10179);//测试用
        $param = input('param.');
        $page = isset($param['page']) ? $param['page'] : 1;
        if (isset($param['type']) && $param['type'] == 'pay_status') {
            $where = ['s.pay_status' => 0, 's.sign_status' => 0, 's.user_id' => $userInfo['user_id']];
        }
        if (isset($param['type']) && $param['type'] == 'sign_status') {//待出行，待核销同一个
            $where = ['s.sign_status' => 0, 's.pay_status' => 1, 's.user_id' => $userInfo['user_id']];
        }
        if (isset($param['type']) && $param['type'] == 'all') {
            $where = ['s.user_id' => $userInfo['user_id']];
        }
        if (isset($param['type']) && $param['type'] == 'signup') {
            $where = ['s.sign_status' => 1, 's.user_id' => $userInfo['user_id']];
        }
        if (isset($param['type']) && $param['type'] == 'expire') {
            $where = ['s.sign_status' => 0, 's.pay_status' => 1, 's.user_id' => $userInfo['user_id']];
        }

        $a = Db::name('activity_sign')
            ->alias('s')
            ->join('activity a', 's.activity_id = a.activity_id')
            ->join('upload_file u', 'a.image_id = u.file_id')
            ->field('a.*,u.*,s.activity_id,s.user_id,s.pay_status,s.sign_status,s.people_num as sign_people')
            ->where('a.wxapp_id', $this->wxapp_id)
            ->where($where);
        if (isset($param['type']) && $param['type'] == 'expire') {
            $a->whereTime('end_time', '<', date('Y-m-d H:i:s', time()));
        }
        if (isset($param['type']) && $param['type'] == 'sign_status') {
            $a->whereTime('end_time', '>', date('Y-m-d H:i:s', time()));
        }
        $data = $a->page($page, 5)->select()->toArray();
        $totalPage = ceil($a->count() / 5);
        foreach ($data as &$v) {
            if ($v['pay_status'] == 0) {
                $v['status'] = 1;//待支付
            }
            if ($v['sign_status'] == 0 && $v['pay_status'] == 1) {
                $v['status'] = 2;//待核销
            }
            if ($v['sign_status'] == 0 && $v['pay_status'] == 1 && $v['end_time'] < date('Y-m-d H:i:s', time())) {
                $v['status'] = 4;//过期
            }
            if ($v['sign_status'] == 1) {
                $v['status'] = 3;//已核销
            }
            $v['start_time'] = date('Y-m-d H:i', strtotime($v['start_time']));
            $v['end_time'] = date('Y-m-d H:i', strtotime($v['end_time']));
            $v['start_sign'] = date('Y-m-d H:i', strtotime($v['start_sign']));
            $v['end_sign'] = date('Y-m-d H:i', strtotime($v['end_sign']));
            $v['theme_label'] = explode(",", $v['theme_label']);
        }

        return $this->renderSuccess(['data' => $data, 'totalPage' => $totalPage]);
    }

    /**
     * 老会员认领身份
     * @param array $post
     * @return string
     */
    public function claim()
    {
        $param = input('param.');
        // 当前用户信息
        $userInfo = $this->getUser();
        if (isset($param['number']) && !empty($param['number'])) {
            //var_dump($param['number']);die();
            $old_user = Db::name('old_user')->where('wxapp_id', $this->wxapp_id)->where('vip_number|card_id', '=', $param['number'])->find();
            if (!$old_user) {
                return $this->renderError('未找到会员信息');
            }
            if ($old_user['status'] == 1) {
                return $this->renderError('该会员身份已经认领过了');//废弃不要了，又用了
            }
            if ($old_user['gender'] == '男') {
                $old_user['gender'] = 1;
            } elseif ($old_user['gender'] == '女') {
                $old_user['gender'] = 2;
            } else {
                $old_user['gender'] = 0;
            }
            $team_info = Db::name('team')->where('wxapp_id', $this->wxapp_id)->where('team_no', $old_user['team_num'])->find();
            if (!$team_info) {
                return $this->renderError('未找到会员服务队，编号：' . $old_user['team_num']);
            }
            $res7 = Db::name('user')->where('wxapp_id', $this->wxapp_id)->where('vip_number', $old_user['vip_number'])->find();
            $res8 = Db::name('user')->where('wxapp_id', $this->wxapp_id)->where('card_id', $old_user['card_id'])->find();
            if ($res7 || $res8) {
                return $this->renderError('该会员号/身份证已（存在）被认领');
            }
            $res = Db::name('user')->where('wxapp_id', $this->wxapp_id)->where('user_id', $userInfo['user_id'])->update([
                'nickName' => $old_user['name'],
                'gender' => $old_user['gender'],
                'team_id' => $team_info['team_id'],
                'birth_date' => date("Y-m-d", strtotime($old_user['birth_date'])),
                'vip_number' => $old_user['vip_number'],
                'phone' => $old_user['phone'],
                'company_name' => $old_user['company_name'],
                'vip_type' => $old_user['vip_type'],
                'add_date' => date("Y-m-d", strtotime($old_user['add_date'])),
                'card_id' => $old_user['card_id'],
                'e_mail' => $old_user['e_mail'],
                'user_address' => $old_user['address'],
            ]);
            if (!$res) {
                //Log::record($log, 'error');
                return $this->renderError('认领出错了~');
            }
            if ($old_user['user_id'] == 14523) {//叮当测试身份不改认领状态
                Db::name('old_user')->where('wxapp_id', $this->wxapp_id)->where('card_id', $old_user['card_id'])->update(['user_uid' => $userInfo['user_id']]);
            } else {
                Db::name('old_user')->where('wxapp_id', $this->wxapp_id)->where('card_id', $old_user['card_id'])->update(['status' => 1, 'user_uid' => $userInfo['user_id']]);//不限老会员身份领取次数了，202030602又限制了
            }
            $old_donate = Db::name('old_donate')->where('wxapp_id', $this->wxapp_id)->where('vip_number', $old_user['vip_number'])->find();
            if ($old_donate) {
                Db::name('user')->where('wxapp_id', $this->wxapp_id)->where('user_id', $userInfo['user_id'])->update(['donate' => $old_donate['donate_total']]);
            }
            return $this->renderSuccess(['team_id' => $team_info['team_id']]);
        }
        return $this->renderError('参数有误');
    }

    //服务队信息
    public function teamInfo()
    {
        $team = Db::name('team')->where('wxapp_id', $this->wxapp_id)->select()->toArray();
        return $this->renderSuccess($team);
    }

    //提交入会申请
    public function applyFor()
    {
        $user = $this->getUser();
        $param = input('param.');
        $param['update_time'] = date('Y-m-d H:i:s');
        $param['user_id'] = $user['user_id'];
        $res1 = Db::name('old_user')->where('card_id', $param['card_id'])->find();
        if ($res1) {
            return $this->renderError('申请失败，该身份证信息已存在');
        }
        unset($param['token']);
        $res = Db::name('apply_member')->where('user_id', $user['user_id'])->find();
        if ($res) {
            $param['examine_status'] = 0;
            Db::startTrans();
            try {
                Db::name('apply_member')->where('user_id', $user['user_id'])->update($param);
                Db::commit();
                return $this->renderSuccess([], '提交成功，请等待审核');
            } catch (\Exception $e) {
                Db::rollback();
                return $this->renderError($e->getMessage() . '操作失败');
            }
        } else {
            Db::startTrans();
            try {
                $param['create_time'] = date('Y-m-d H:i:s');
                Db::name('apply_member')->insert($param);
                Db::commit();
                return $this->renderSuccess([], '提交成功，请等待审核');
            } catch (\Exception $e) {
                Db::rollback();
                return $this->renderError($e->getMessage() . '操作失败');
            }
        }
    }

    //提交入会申请(副表)
    public function applyForSecondary()
    {
        $user = $this->getUser();
        $param = input('param.');
        $param['update_time'] = date('Y-m-d H:i:s');
        $param['user_id'] = $user['user_id'];
        unset($param['token']);
        $res = Db::name('apply_member_secondary')->where('user_id', $user['user_id'])->find();
        if ($res) {
            Db::startTrans();
            try {
                Db::name('apply_member_secondary')->where('user_id', $user['user_id'])->update($param);
                Db::commit();
                return $this->renderSuccess([], '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                return $this->renderError($e->getMessage() . '操作失败');
            }
        } else {
            Db::startTrans();
            try {
                $param['create_time'] = date('Y-m-d H:i:s');
                Db::name('apply_member_secondary')->insert($param);
                Db::commit();
                return $this->renderSuccess([], '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                return $this->renderError($e->getMessage() . '操作失败');
            }
        }
    }

    //查询我的入会申请接口
    public function myApplyFor()
    {
        $user = $this->getUser();
        $info = Db::name('apply_member')->where('user_id', $user['user_id'])->find();
        if ($info) {
            $a = Db::name('upload_file')->find($info['carda_id']);
            $b = Db::name('upload_file')->find($info['cardb_id']);
            $info['image_a'] = $a['file_url'] . '/' . $a['file_name'];
            $info['image_b'] = $b['file_url'] . '/' . $b['file_name'];
        }
        $info_second = Db::name('apply_member_secondary')->where('user_id', $user['user_id'])->find();
        if (!$info_second) {
            $info_second = [];
        }
        if (!$info) {
            $info = false;
        }
        return $this->renderSuccess(['data' => $info, 'second_data' => $info_second]);
    }

    //入会填表说明
    public function addMember()
    {
        $explain = Setting::getItem('notice', $this->wxapp_id)['explain'];
        return $this->renderSuccess(htmlspecialchars_decode($explain));
    }

    //更新用户头像和昵称
    public function upUserInfo()
    {
        $data = input('param.');
        $user = $this->getUser(false);
        if (!$user) {
            $this->renderError('用户信息有误');
        }
        if (isset($data['avatarUrl'])) {
            $avatarUrl = $this->saveBase64($data['avatarUrl']);
            if (isset($avatarUrl['url'])) {
                Db::name('user')->where('user_id', $user['user_id'])->update(['avatarUrl' => $avatarUrl['url']]);
            } else {
                $this->renderError($avatarUrl['msg']);
            }
        }
        if (isset($data['nickName'])) {
            Db::name('user')->where('user_id', $user['user_id'])->update(['nickName' => $data['nickName']]);
        }
        return $this->renderSuccess('操作成功');
    }

    private function saveBase64($base64_image_content)
    {

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            //图片后缀
            $type = $result[2];
            //保存位置--图片名
            $image_name = date('His') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT) . "." . $type;
            $image_file_path = '/wxavatar/' . date('Ymd');
            $image_file = WEB_PATH . 'uploads' . $image_file_path;
            $imge_real_url = $image_file . '/' . $image_name;
            $imge_web_url = $image_file_path . '/' . $image_name;
            if (!file_exists($image_file)) {
                mkdir($image_file, 0777, true);
                fopen($image_file . '\\' . $image_name, "w");
            }
            //解码
            $decode = base64_decode(str_replace($result[1], '', $base64_image_content));
            if (file_put_contents($imge_real_url, $decode)) {
                $data['code'] = 0;
                $data['imageName'] = $image_name;
                $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                //$wzurl = $protocol . $_SERVER['HTTP_HOST'];
                $data['url'] = $protocol . $_SERVER['HTTP_HOST'] . '/uploads' . $imge_web_url;
                $data['msg'] = '保存成功！';
            } else {
                $data['code'] = 1;
                $data['imgageName'] = '';
                $data['url'] = '';
                $data['msg'] = '图片保存失败！';
            }
        } else {
            $data['code'] = 1;
            $data['imgageName'] = '';
            $data['url'] = '';
            $data['msg'] = 'base64图片格式有误！';
        }
        return $data;
    }

}
